
<template>
    <div class="threeJsPrc63">
      <div class="myCanvas" ref="myCanvas"></div>
    </div>
</template>

<script lang="ts">
import { Vue, Options } from 'vue-property-decorator';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
const scene = new THREE.Scene();
scene.add(new THREE.AxesHelper(250));
const camera = new THREE.PerspectiveCamera();
camera.fov = 70;
camera.near = 1;
camera.near = 10000;
const renderer = new THREE.WebGLRenderer({
  alpha: true,
});
renderer.debug.checkShaderErrors = false;
renderer.setClearColor(0xb9d3ff, 1);

@Options({ components: {
} })
export default class ThreeJsPrc63 extends Vue {
  public rect: DOMRect|null=null;
  public dpr =750 / window.innerWidth;
  public controls!: OrbitControls;

  public mounted() {
    this.rect = (this.$el as HTMLElement).getBoundingClientRect();
    (this.$refs.myCanvas as HTMLDivElement).append(renderer.domElement);
    renderer.setPixelRatio(this.dpr);
    renderer.setSize(this.rect.width, this.rect.height, false);
    camera.aspect = this.rect.width / this.rect.height;
    camera.position.set(200, 100, 200);
    camera.lookAt(scene.position);
    renderer.render(scene, camera);

    const geometry = new THREE.BoxGeometry(50, 50, 50);
    const material = new THREE.MeshLambertMaterial({
      color: 0xffff00,
    });
    const mesh = new THREE.Mesh(geometry, material);
    // mesh的本地坐标设置为(50, 0, 0)
    mesh.position.set(50, 0, 0);
    const group = new THREE.Group();
    // group本地坐标设置和mesh一样设置为(50, 0, 0)
    // mesh父对象设置position会影响得到mesh的世界坐标
    group.position.set(10, 0, 0);
    group.add(mesh);
    scene.add(group);

    // .position属性获得本地坐标
    console.log('本地坐标', mesh.position);

    // getWorldPosition()方法获得世界坐标
    // 该语句默认在threejs渲染的过程中执行,如果渲染之前想获得世界矩阵属性、世界位置属性等属性，需要通过代码更新
    scene.updateMatrixWorld(true);
    const worldPosition = new THREE.Vector3();
    mesh.getWorldPosition(worldPosition);
    console.log('世界坐标', worldPosition);

    renderer.setAnimationLoop(() => {
      renderer.render(scene, camera);
    });

    this.controls = new OrbitControls(camera, renderer.domElement);
  }
}
</script>

<style lang="postcss" scoped>
.threeJsPrc63{
  touch-action: none;
  width: 100%;
  height: 100%;
  background: grey;
}
</style>
